Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
- Your algorithm should have a linear runtime complexity.
- Could you implement it without using extra memory?
题目大意:给定一个数组,除了一个数以外其余所有数都出现了三次,找出该数。要求事件复杂度O(N),空间复杂度O(1)
题目难度:Medium
/**
* Created by gzdaijie on 16/6/18
* 记录每一个int位出现的次数,若是三的倍数,说明出现了三次
*/
public class Solution {
public int singleNumber(int[] nums) {
int[] tag = new int[32];
int result = 0;
for (int i = 0; i < 32; i++) {
for (int j = 0; j < nums.length; j++) {
tag[i] += (nums[j] >> i) & 1;
}
}
for (int i = 0; i < 32; i++) {
if (tag[i] % 3 != 0) result += 1 << i;
}
return result;
}
}